/**
 * Copyright &copy; 2012-2017 <a href="https://vivo.com/">vivo</a> All rights reserved.
 */
package com.vivo.system.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.vivo.system.entity.SmsTemplate;
import com.vivo.system.service.SmsTemplateService;

import java.util.List;

/**
 * 短信模板Controller
 * @author jyangye
 * @version 2018-03-06
 */
@Controller
@RequestMapping(value = "${adminPath}/system/smsTemplate")
public class SmsTemplateController extends BaseController {

	@Autowired
	private SmsTemplateService smsTemplateService;
	
	@ModelAttribute
	public SmsTemplate get(@RequestParam(required=false) String id) {
		SmsTemplate entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = smsTemplateService.get(id);
		}
		if (entity == null){
			entity = new SmsTemplate();
		}
		return entity;
	}
	
	@RequiresPermissions("system:smsTemplate:view")
	@RequestMapping(value = {"list", ""})
	public String list(SmsTemplate smsTemplate, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SmsTemplate> page = smsTemplateService.findPage(new Page<SmsTemplate>(request, response), smsTemplate);

		if (page.getList().size() == 0) {
		    SmsTemplate smsT = new SmsTemplate();
		    smsT.setComp(UserUtils.getUser().getCompany());
		    smsTemplateService.save(smsT);

		    page.getList().add(smsT);
        }
		model.addAttribute("page", page);
		return "vivo/system/smsTemplateList";
	}

	@RequiresPermissions("system:smsTemplate:view")
	@RequestMapping(value = "form")
	public String form(SmsTemplate smsTemplate, String type, Model model) {
	    int typeI = Integer.parseInt(type);

	    switch (typeI) {
	        // 应聘邀约
            case 0:
                smsTemplate.setMsg("可用参数{name}-姓名");
                smsTemplate.setTempMsg(smsTemplate.getInvite());
                break;

                // 初试通知
            case 1:
                smsTemplate.setMsg("可用参数{name}-姓名, {post}-岗位, {time}-时间,  {address}-地点");
                smsTemplate.setTempMsg(smsTemplate.getFirst());
                break;

                // 复试通知
            case 2:
                smsTemplate.setMsg("可用参数{name}-姓名, {post}-岗位, {time}-时间,  {address}-地点");
                smsTemplate.setTempMsg(smsTemplate.getFstz());
                break;

                // 二次复试通知
            case 3:
                smsTemplate.setMsg("可用参数{name}-姓名, {post}-岗位, {time}-时间,  {address}-地点");
                smsTemplate.setTempMsg(smsTemplate.getFsstz());
                break;

                // 体检通知
            case 4:
                smsTemplate.setMsg("可用参数{name}-姓名, {time}-时间,  {address}-地点");
                smsTemplate.setTempMsg(smsTemplate.getTjtz());
                break;

                // 入职办理通知
            case 5:
                smsTemplate.setMsg("可用参数{name}-姓名, {time}-时间");
                smsTemplate.setTempMsg(smsTemplate.getInduty());
                break;

            default:
                break;
        }

	    model.addAttribute("type", type);
		model.addAttribute("smsTemplate", smsTemplate);
		return "vivo/system/smsTemplateForm";
	}

	@RequiresPermissions("system:smsTemplate:edit")
	@RequestMapping(value = "save")
	public String save(SmsTemplate smsTemplate, String type, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, smsTemplate)){
			return form(smsTemplate, type, model);
		}

        int typeI = Integer.parseInt(type);

        switch (typeI) {
            // 应聘邀约
            case 0:
                smsTemplate.setInvite(smsTemplate.getTempMsg());
                break;

            // 初试通知
            case 1:
                smsTemplate.setFirst(smsTemplate.getTempMsg());
                break;

            // 复试通知
            case 2:
                smsTemplate.setFstz(smsTemplate.getTempMsg());
                break;

            // 二次复试通知
            case 3:
                smsTemplate.setFsstz(smsTemplate.getTempMsg());
                break;

            // 体检通知
            case 4:
                smsTemplate.setTjtz(smsTemplate.getTempMsg());
                break;

            // 入职办理通知
            case 5:
                smsTemplate.setInduty(smsTemplate.getTempMsg());
                break;

            default:
                break;
        }

		smsTemplateService.save(smsTemplate);
		addMessage(redirectAttributes, "保存短信模板成功");
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
	}
	
	@RequiresPermissions("system:smsTemplate:edit")
	@RequestMapping(value = "delete")
	public String delete(SmsTemplate smsTemplate, RedirectAttributes redirectAttributes) {
		smsTemplateService.delete(smsTemplate);
		addMessage(redirectAttributes, "删除短信模板成功");
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
	}

	/**
	 * 批量删除短信模板
	 */
	@RequiresPermissions("system:smsTemplate:edit")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			smsTemplateService.delete(smsTemplateService.get(id));
		}
		addMessage(redirectAttributes, "删除短信模板成功");
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("system:smsTemplate:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(SmsTemplate smsTemplate, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "短信模板"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<SmsTemplate> page = smsTemplateService.findPage(new Page<SmsTemplate>(request, response, -1), smsTemplate);
    		new ExportExcel("短信模板", SmsTemplate.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出短信模板记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("system:smsTemplate:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<SmsTemplate> list = ei.getDataList(SmsTemplate.class);
			for (SmsTemplate smsTemplate : list){
				try{
					smsTemplateService.save(smsTemplate);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条短信模板记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条短信模板记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入短信模板失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
    }

	/**
	 * 下载导入{functionNameSimple}数据模板
	 */
	@RequiresPermissions("system:smsTemplate:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "短信模板数据导入模板.xlsx";
    		List<SmsTemplate> list = Lists.newArrayList();
    		new ExportExcel("短信模板数据", SmsTemplate.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/smsTemplate/?repage";
    }

}